<?php

namespace App\Service\Common;

use AlibabaCloud\SDK\Mts\V20140618\Models\AddWaterMarkTemplateRequest;
use AlibabaCloud\SDK\Mts\V20140618\Models\QueryJobListRequest;
use AlibabaCloud\SDK\Mts\V20140618\Models\SubmitJobsRequest;
use AlibabaCloud\SDK\Mts\V20140618\Mts;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Tea;
use AlibabaCloud\Tea\Utils\Utils;
use App\Models\Common\FileTranscodingJobModel;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Mts\V20140618\Models\CreateFpShotDBRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Mts\V20140618\Models\SubmitAnalysisJobRequest;
use Illuminate\Support\Facades\Log;

class UploadTranscoding
{

    /**
     * 创建客户端
     * @param $accessKeyId
     * @param $accessKeySecret
     * @param string $endpoint
     * @return Mts
     */
    public static function createClient(
        $accessKeyId,
        $accessKeySecret,
        string $endpoint = 'mts.cn-hangzhou.aliyuncs.com'
    ): Mts {
        $config = new Config([
            "accessKeyId"     => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = $endpoint;
        return new Mts($config);
    }

    //创建水印模版
    public static function createWatermarkTemplate($path, $params = [])
    {
        if (empty($params)) {
            $params = config('file-transcoding.kf-file');
        }
        $input                       = [
            'Bucket'   => 'kf-file',
            'Location' => 'oss-cn-hangzhou',
            'Object'   => 'https://file.51kuafu.com/83/e0/f8ff1cbe157c1b0a89044ef0aac35a20fbc12113aff14d4f657b812b3a83.png'
        ];
        $client                      = self::createClient($params['accessKeyId'], $params['accessKeySecret'],
            $params['endpoint']);
        $addWaterMarkTemplateRequest = new AddWaterMarkTemplateRequest([
            "name"   => "checkVideo",
            "config" => json_encode($input),
        ]);
        $runtime                     = new RuntimeOptions([]);
        try {
            $resp  = $client->addWaterMarkTemplateWithOptions($addWaterMarkTemplateRequest, $runtime);
            $jobId = $resp->toMap()['body']['JobResultList']['JobResult'][0]['Job']['JobId'] ?? '';
        } catch (\Exception $error) {
            Log::info('视频转码失败(请调试得因)-FilePath:' . $path);
        }

        return $jobId;
    }

    /**
     * 文件转码
     * @param $path 22/11/de3aa22056ad39b77628c72d66661cc7c808aacfbdf4139ce21b0d66309b.mp4
     * @param array $params 配置文件
     * @param string $watermarkTemplate 水印图片
     * @param string|null $outputObject
     * @return string
     */
    public static function asyncFileTranscoding(
        $path,
        array $params = [],
        string $watermarkTemplate = '',
        ?string $outputObject = null
    ): string {
        if (empty($params)) {
            $params = config('file-transcoding.kf-file');
        }

        $input = [
            'Bucket'   => $params['inputBucket'],
            'Object'   => $path,
            'Location' => $params['location']
        ];

        $resPath = substr($path, 0, strrpos($path, '.'));
        $outputs = [
            [
                'OutputObject' => $outputObject ?? $resPath . '_encoded.mp4',
                'Container'    => [
                    'Format' => $params['format'],
                ],
                'TemplateId'   => $params['templateId'],
                'TransConfig'  => [
                    'TransMode' => 'CBR',  // 固定码率模式
                ],
                'Video'        => [
                    'Bitrate' => -1,  // 输入视频原始码率
                ]
            ]
        ];

        if (mb_strlen($watermarkTemplate)) {
            $watermarkTemplate        = [
                'InputFile' => [
                    'Bucket'   => $params['inputBucket'],
                    'Location' => $params['location'],
                    'Object'   => $watermarkTemplate
                ],
                'Width'     => 0.5,
                'Dx'        => 0.05,
                'Dy'        => 0.05,
                'ReferPos'  => 'BottomLeft',
            ];
            $outputs[0]['WaterMarks'] = json_encode([$watermarkTemplate]);
        }


        $jobId = '';
        //创建客户端
        $client            = self::createClient($params['accessKeyId'], $params['accessKeySecret'],
            $params['endpoint']);
        $submitJobsRequest = new SubmitJobsRequest([
            "input"        => json_encode($input),
            "outputs"      => json_encode($outputs),
            "outputBucket" => $params['outputBucket'],
            "pipelineId"   => $params['pipelineId'],
        ]);
        $runtime           = new RuntimeOptions([]);
        try {
            $resp  = $client->submitJobsWithOptions($submitJobsRequest, $runtime);
            $jobId = $resp->toMap()['body']['JobResultList']['JobResult'][0]['Job']['JobId'] ?? '';
        } catch (\Exception $error) {
            Log::info('视频转码失败(请调试得因)-FilePath:' . $path);
        }

        return $jobId;
    }


    /**
     * 获得JobId的任务状态（转码进度）
     * @param string $jobId
     * @param array $params
     * @return int|mixed
     */
    public static function getWorkFile(string $jobId = '', array $params = [])
    {
        if (empty($params)) {
            $params = config('file-transcoding.kf-file');
        }


        $client              = self::createClient($params['accessKeyId'], $params['accessKeySecret']);
        $queryJobListRequest = new QueryJobListRequest([
            //需要查询的转码作业ID
            "jobIds" => $jobId
        ]);
        $runtime             = new RuntimeOptions([]);
        try {
            $res     = $client->queryJobListWithOptions($queryJobListRequest, $runtime);
            $percent = $res->body->toMap()['JobList']['Job'][0]['Percent'] ?? -1;  //进度百分比
        } catch (\Exception $error) {
            $percent = -1;
        }
        //添加日志
        if ($percent == -1) {
            Log::info('获得进度百分比失败-JobId:' . $jobId);
        }
        return $percent;
    }
}
